﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CarbonExchange.Bll;
using Acms.DataControls;

public partial class Admin_Countries : PageBase
{
    protected void Page_Load(object sender, EventArgs e)
    {
        dsCountries.Select += new EventHandler<EventDrivenDataSourceSelectEventArgs>(dsCountries_Select);
        dsCountries.Insert += new EventHandler<EventDrivenDataSourcePerformOperationEventArgs>(dsCountries_Insert);
        dsCountries.Update += new EventHandler<EventDrivenDataSourcePerformOperationEventArgs>(dsCountries_Update);
        dsCountries.Delete += new EventHandler<EventDrivenDataSourcePerformOperationEventArgs>(dsCountries_Delete);
    }

    private CountryFactory countryFactory;
    protected CountryFactory GetCountryFactory()
    {
        countryFactory = countryFactory ?? new CountryFactory();
        return countryFactory;
    }


    void dsCountries_Delete(object sender, EventDrivenDataSourcePerformOperationEventArgs e)
    {
        var id = (int)e.Keys["Id"];
        var tmp = GetCountryFactory().GetById(id);
        if (tmp != null)
        {
            GetCountryFactory().Delete(tmp);
            e.RowsChanged = 1;
        }
    }

    void dsCountries_Update(object sender, EventDrivenDataSourcePerformOperationEventArgs e)
    {
        if (IsValid)
        {
            var id = (int)e.Keys["Id"];
            var tmp = GetCountryFactory().GetById(id);
            if (tmp != null)
            {
                tmp.Locale = e.NewValues["Locale"] as string;
                GetCountryFactory().Save(tmp);
                e.RowsChanged = 1;
            }
        }
    }

    void dsCountries_Insert(object sender, EventDrivenDataSourcePerformOperationEventArgs e)
    {
        if (IsValid)
        {
            Country tmp = new Country(AcmsContext.SiteId);
            tmp.Locale = e.NewValues["Locale"] as string;
            GetCountryFactory().Save(tmp);

            e.RowsChanged = 1;
        }
    }

    void dsCountries_Select(object sender, EventDrivenDataSourceSelectEventArgs e)
    {
        //convert to array to force get then sort

        var tmp = GetCountryFactory().GetAllBySiteId(AcmsContext.SiteId).ToArray().AsQueryable();
        tmp = tmp.OrderBy(x => x.Name);
        e.SetData(tmp);
    }
}
